﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxTabControl;
using DevExpress.Web.ASPxEditors;
using System.Data;
using DevExpress.Web.ASPxDataView;
using Touchmax;

public partial class OrderEdit :Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
            string on = Request.QueryString["no"] ?? "0";
        if (!IsPostBack)
        {
            Session["CfsImp"] = null;
            int no = SafeValue.SafeInt(on, 0);
            if (no > 0)
            {
                Session["CfsImp"] = "JobNo='" + no + "'";
            }
            else if (Session["CfsImp"] == null)
            {
                this.grid_Order.AddNewRow();
            }

        }
        
        if (Session["CfsImp"] != null)
        {

            this.dsJobOrder.FilterExpression = Session["CfsImp"].ToString();
            if (this.grid_Order.GetRow(0) != null)
                this.grid_Order.StartEdit(0);
            this.dsVehicle.FilterExpression = "JobOrder='"+on+"'";
            this.dsInvoice.FilterExpression = " DocType='Invoice' and JobOrder='" + on + "'";
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    #region job order
    protected void grid_Order_Init(object sender, EventArgs e)
    {
        ASPxGridView grd = sender as ASPxGridView;
        if (grd != null)
        {
            grd.ForceDataRowType(typeof(Touchmax.OpOrder));
        }
    }
    protected void grid_Order_InitNewRow(object sender, DevExpress.Web.Data.ASPxDataInitNewRowEventArgs e)
    {
        e.NewValues["JobNo"] = "-";
        e.NewValues["JobDate"] = DateTime.Today;}
    private void Save()
    {
        try
        {
            ASPxTextBox orderNo = this.grid_Order.FindEditFormTemplateControl("txt_OrderNo") as ASPxTextBox;

            string refN = orderNo.Text;
            Wilson.ORMapper.OPathQuery query = new Wilson.ORMapper.OPathQuery(typeof(Touchmax.OpOrder), "JobNo='" + refN + "'");
            Touchmax.OpOrder jo = Touchmax.Manager.ORManager.GetObject(query) as Touchmax.OpOrder;
            bool isNew = false;
            if (jo == null)
            {
                jo = new Touchmax.OpOrder();
                isNew = true;
                refN = GetNo("CFS-JOB");
                jo.JobNo = refN;
                jo.UserId = HttpContext.Current.User.Identity.Name;
                jo.EntryDate = DateTime.Now;
            }
            ASPxDropDownEdit custId = this.grid_Order.FindEditFormTemplateControl("de_Cust") as ASPxDropDownEdit;
            jo.CustId = custId.Value.ToString();
            ASPxDateEdit jobDate= this.grid_Order.FindEditFormTemplateControl("date_JobDate") as ASPxDateEdit;
            jo.JobDate = jobDate.Date;
            ASPxTextBox custContact = this.grid_Order.FindEditFormTemplateControl("txt_CustContact") as ASPxTextBox;
            jo.CustContact = custContact.Text;

            ASPxComboBox jobSource = this.grid_Order.FindEditFormTemplateControl("cmb_JobSource") as ASPxComboBox;
            jo.JobSource = jobSource.Text;
            ASPxComboBox jobType = this.grid_Order.FindEditFormTemplateControl("cmb_JobType") as ASPxComboBox;
            jo.JobType = jobType.Text;

            ASPxMemo rmk = this.grid_Order.FindEditFormTemplateControl("txt_Rmk") as ASPxMemo;
            jo.Remark = rmk.Text;
            ASPxComboBox tehnicain = this.grid_Order.FindEditFormTemplateControl("cmb_Tehnician") as ASPxComboBox;
            jo.Tehnician = tehnicain.Text;

            ASPxComboBox jobStatus = this.grid_Order.FindEditFormTemplateControl("cmb_JobStatus") as ASPxComboBox;
            jo.JobStatus = jobStatus.Text;

          if (isNew)
            {
                Touchmax.Manager.ORManager.StartTracking(jo, Wilson.ORMapper.InitialState.Inserted);
                Touchmax.Manager.ORManager.PersistChanges(jo);
            }
            else
            {
                Touchmax.Manager.ORManager.StartTracking(jo, Wilson.ORMapper.InitialState.Updated);
                Touchmax.Manager.ORManager.PersistChanges(jo);
            }
            if (isNew)
            {
                SetNo(refN, "CFS-JOB");
                Session["CfsImp"] = "JobNo='" + refN + "'";
                this.dsJobOrder.FilterExpression = "JobNo='" + refN + "'";

                // orderNo.Text = refN;
                if (this.grid_Order.GetRow(0) != null)
                    this.grid_Order.StartEdit(0);
            }
        }
        catch (Exception ex)
        { throw new Exception(ex.Message); }
    }
    private string GetNo(string noType)
    {
        string sql = "select Counter from XXSetup where Category='" + noType + "'";
        int cnt = SafeValue.SafeInt(Touchmax.Manager.ORManager.ExecuteScalar(sql), 0) + 1;

        return cnt.ToString();

    }
    private void SetNo(string no,string noType)
    {
        string sql = string.Format("update XXSetup set counter='{0}' where category='{1}'",no, noType);
       int res= Touchmax.Manager.ORManager.ExecuteCommand(sql);
    }
    protected void grid_Order_CustomDataCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomDataCallbackEventArgs e)
    {
        string s = e.Parameters;
        if (s == "IssueInvoice")
        {
            ASPxTextBox orderNo = this.grid_Order.FindEditFormTemplateControl("txt_OrderNo") as ASPxTextBox;
            ASPxTextBox custId = this.grid_Order.FindEditFormTemplateControl("txt_CustCode") as ASPxTextBox;
            string inv=IssueInvoice(orderNo.Text, custId.Text);
            if (inv.Length > 0 && inv.Length < 10)
                e.Result = "Issue invoice " + inv + " successful";
            else
                e.Result = inv;
        }

    }
    private string IssueInvoice(string sn, string custId)
    {
        string invN = "";
        string sql = "SELECT SequenceId FROM OpVehicle WHERE (JobOrder = '" + sn + "') AND (Status = 'Complete')";
        DataTable tab = Touchmax.Manager.ORManager.GetDataSet(sql).Tables[0];
        if (tab.Rows.Count > 0)
        {
            invN = GetNo("Invoice");
            try
            {
                string userName = HttpContext.Current.User.Identity.Name;
                OpInvoice inv = new OpInvoice();
                inv.DocNo = invN;
                inv.UserId = userName;
                inv.DocType = "INVOICE";
                inv.CustId = custId;
                inv.BranchId = "1001";
                inv.JobOrder = sn;
                inv.DocDate = DateTime.Today;
                inv.DocNo = invN.ToString();

                inv.Term = "";
                inv.Remark = "";
                Manager.ORManager.StartTracking(inv, Wilson.ORMapper.InitialState.Inserted);
                Manager.ORManager.PersistChanges(inv);
                SetNo(invN, "Invoice");

                int index = 1;
                for (int i = 0; i < tab.Rows.Count; i++)
                {
                    string oid = tab.Rows[i][0].ToString();
                    sql = "select SequenceId from invoiceDet where DocType='Estimate' and ItemId='" + oid + "'";
                    DataTable tab1 = Touchmax.Manager.ORManager.GetDataSet(sql).Tables[0];
                    for (int j = 0; j < tab1.Rows.Count; j++)
                    {
                        string sql_update = string.Format("update InvoiceDet Set DocNo='{0}',DocLineNo='{1}' where SequenceId='{2}'", invN, index, tab1.Rows[j]["SequenceId"]);
                        int res = Touchmax.Manager.ORManager.ExecuteCommand(sql_update);
                        if (res > 0)
                        {
                            index++;
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                invN = ex.Message;
            }
        }
        else
        {
            invN = "No complete vehicle";
        }
        return invN;
    }
    protected void grid_Order_HtmlEditFormCreated(object sender, ASPxGridViewEditFormEventArgs e)
    {
        ASPxDropDownEdit custId = this.grid_Order.FindEditFormTemplateControl("de_Cust") as ASPxDropDownEdit;
        ASPxMemo address = this.grid_Order.FindEditFormTemplateControl("txtAddress") as ASPxMemo;
        if (custId != null && address != null)
        {
            string sql = "select address,Latitude,Longitude from BoClient where custId='" + custId.Value+ "'";
            DataTable tab = Touchmax.Manager.ORManager.GetDataSet(sql).Tables[0];
            address.Text = SafeValue.SafeString(Touchmax.Manager.ORManager.ExecuteScalar(sql), "");
        }
    }


    #endregion

    #region Vehicle
    protected void grd_Cont_Init(object sender, EventArgs e)
    {
        ASPxGridView grd = sender as ASPxGridView;
        if (grd != null)
        {
            grd.ForceDataRowType(typeof(Touchmax.OpVehicle));
        }
    }
    protected void grd_Cont_BeforePerformDataSelect(object sender, EventArgs e)
    {
   }
    protected void grd_Cont_InitNewRow(object sender, DevExpress.Web.Data.ASPxDataInitNewRowEventArgs e)
    {
      //  string oid = (sender as ASPxGridView).GetMasterRowKeyValue().ToString();
        //e.NewValues["ContNo"] = "";// order.ContNo;
        //e.NewValues["SealNo"] = "";//order.SealNo;
        //e.NewValues["Ft20"] = 0;
        //e.NewValues["Ft40"] = 0;
        //e.NewValues["Ft45"] = 0;
        //e.NewValues["FtType"] = "GP";
        //e.NewValues["ContStatus"] = "PENDING";
        //e.NewValues["ScheduleDate"] = new DateTime(1900,1,1);
        //e.NewValues["ScheduleTime"] = " ";
    }
    protected void grd_Cont_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
        ASPxTextBox orderNoCtr = this.grid_Order.FindEditFormTemplateControl("txt_OrderNo") as ASPxTextBox;
        if (orderNoCtr != null)
        {
            string orderNo = orderNoCtr.Text;//Touchmax.Manager.ORManager.ExecuteScalar("select jobNo from serviceOrder where Oid='" + orderNoCtr.Text + "'").ToString();
            e.NewValues["JobOrder"] = orderNo;

            e.NewValues["UserId"] = HttpContext.Current.User.Identity.Name;
            e.NewValues["EntryDate"] = DateTime.Now;
        }
    }
    protected void grd_Cont_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    { }
    protected void grd_Cont_RowInserted(object sender, DevExpress.Web.Data.ASPxDataInsertedEventArgs e)
    {

    }
    protected void grd_Cont_RowUpdated(object sender, DevExpress.Web.Data.ASPxDataUpdatedEventArgs e)
    {

    }
    protected void grd_Cont_HtmlRowPrepared(object sender, ASPxGridViewTableRowEventArgs e)
    {
        if (e.RowType != DevExpress.Web.ASPxGridView.GridViewRowType.Data) return;
        ASPxLabel label = this.grd_Cont.FindRowCellTemplateControl(e.VisibleIndex, null, "lab_Status") as ASPxLabel;
        if (label == null) return;
        if (label.Text=="Complete"||label.Text=="Bill")
        {
            //e.Row.ForeColor = System.Drawing.Color.;
            //if (label != null)
            //{
            //    label.Text = "         ";
            //    label.BackColor=System.Drawing.Color.Red;
            //}
             e.Row.BackColor = System.Drawing.Color.LightGreen;
       }
        else
        {
            //e.Row.Cells[2].BackColor = System.Drawing.Color.LightGreen;

        }
    }
    #endregion
    protected void Grid_Invoice_Import_DataSelect(object sender, EventArgs e)
    {
        //ASPxGridView grd = sender as ASPxGridView;
        //string sql = "select JobOrderNo from XWJobOrder where Oid='" + SafeValue.SafeInt(grd.GetMasterRowKeyValue(), 0) + "'";
        //this.dsInvoice.FilterExpression = " DocType='Invoice' and JobOrder='" + SafeValue.SafeString(Touchmax.Manager.ORManager.ExecuteScalar(sql), "0") + "'";
        //ASPxTextBox orderNoCtr = this.grid_Order.FindEditFormTemplateControl("txt_OrderNo") as ASPxTextBox;
        //if (orderNoCtr != null)
        //{
        //    this.dsInvoice.FilterExpression = " DocType='Invoice' and JobOrder='" + orderNoCtr.Text + "'";
        //}
    }
    #region photo
    protected void grd_Photo_BeforePerformDataSelect(object sender, EventArgs e)
    {
    }
    protected void gridModel_CustomerCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
    {
   }
   protected void grd_Photo_CustomCallback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
        //ASPxTextBox orderNo = this.grid_Order.FindEditFormTemplateControl("txt_OrderNo") as ASPxTextBox;
        //if (orderNo != null)
        //{
        //    string refN = orderNo.Text;
        //    this.dsJobPhoto.FilterExpression = "OrderNo='"+refN+"'";// 
        //    (sender as ASPxDataView).DataBind();
        //}
    }
   protected void grid_Order_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
    {
        string s = e.Parameters;
        if (s == "Save")
        {
            Save();
        }
    }
     #endregion
   #region Estimate det
   protected void grid_InvDet_Init(object sender, EventArgs e)
    {
        ASPxGridView grd = sender as ASPxGridView;
        if (grd != null)
            grd.ForceDataRowType(typeof(OpInvoiceDet));
    }
    protected void grid_InvDet_BeforePerformDataSelect(object sender, EventArgs e)
    {
        ASPxGridView grd = (sender as ASPxGridView) as ASPxGridView;
        this.dsInvoiceDet.FilterExpression = "DocType='Estimate' and ItemId='" + SafeValue.SafeString(grd.GetMasterRowKeyValue(), "0") + "'";
    }
    protected void grid_InvDet_InitNewRow(object sender, DevExpress.Web.Data.ASPxDataInitNewRowEventArgs e)
    {
        e.NewValues["DocLineNo"] = 0;
        e.NewValues["TotAmt"] = 0;
    }
    protected void grid_InvDet_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
    {
        ASPxGridView grd = sender as ASPxGridView;
        //ASPxSpinEdit item = grd.FindEditFormTemplateControl("spin_det_ItemId") as ASPxSpinEdit;

        e.NewValues["ItemId"] = SafeValue.SafeString(grd.GetMasterRowKeyValue(), "0");
    }
    protected void grid_InvDet_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
        ASPxGridView grd = (sender as ASPxGridView) as ASPxGridView;
        string sql = "select count(DocLineNo) from invoicedet where DocType='Estimate' and ItemId='" + SafeValue.SafeString(grd.GetMasterRowKeyValue(), "0") + "'";
        int lineN = SafeValue.SafeInt(Touchmax.Manager.ORManager.ExecuteScalar(sql), 0) + 1;
       e.NewValues["ItemId"] = SafeValue.SafeString(grd.GetMasterRowKeyValue(), "0");
        e.NewValues["DocType"] = "Estimate";
        sql = "select JobOrder from OpVehicle where SequenceId='" + SafeValue.SafeString(grd.GetMasterRowKeyValue(), "0") + "'";
        e.NewValues["JobOrder"] = SafeValue.SafeString(Touchmax.Manager.ORManager.ExecuteScalar(sql), "") ;
    }
    protected void grid_InvDet_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
    {
    }

    #endregion

    #region select
    protected void gridPopCont_CustomJSProperties(object sender, ASPxGridViewClientJSPropertiesEventArgs e)
    {
        ASPxGridView grid = sender as ASPxGridView;
         object[] keyValues = new object[grid.VisibleRowCount]; ;
         object[] names = new object[grid.VisibleRowCount];
         object[] addresses = new object[grid.VisibleRowCount];
         object[] contacts = new object[grid.VisibleRowCount];
         for (int i = 0; i < grid.VisibleRowCount; i++)
        {
            keyValues[i] = grid.GetRowValues(i, "CustId");
            names[i] = grid.GetRowValues(i, "Name");
             addresses[i] = grid.GetRowValues(i, "Address");
            contacts[i] = grid.GetRowValues(i, "Contact1");
       }
        e.Properties["cpName"] = names;
        e.Properties["cpAddress"] = addresses;
        e.Properties["cpContact"] = contacts;
        e.Properties["cpKeyValues"] = keyValues;
    }
    #endregion

}
